import { ref } from "vue";

const toastRef = ref<any | null>(null);

export const utilsServices = {
  showToast: (text: string) => {
    toastRef.value?.show({
      text,
    });
  },

  /**
   * 获取url中的query，生成键值对
   * @param {string} url 样本url
   * @return {Object} query键值对
   */
  getQueryObject(url: string): { [key: string]: string } {
    if (!url) {
      return {};
    }
    let search = url.substring(url.lastIndexOf("?") + 1);
    let obj: { [key: string]: string } = {};
    let reg = /([^?&=#]+)=([^?&#]*)/g;
    search.replace(reg, function (rs, $1, $2) {
      let name = $1;
      let val = $2;
      obj[name] = val || "";
      return rs;
    });
    return obj;
  },

  getQueryStr(obj: { [key: string]: any }): string {
    if (!obj) {
      return '';
    }
    return Object.getOwnPropertyNames(obj)
      .map((key) => `${key}=${obj[key] ?? ''}`)
      .join('&');
  },
};

export const initToast = (toast: any) => {
  toastRef.value = toast;
};
